from pydantic import BaseModel, EmailStr, validator
from typing import Optional, List
from datetime import datetime


class UserRegister(BaseModel):
    """用户注册请求"""
    username: str
    email: EmailStr
    password: str
    
    @validator('username')
    def validate_username(cls, v):
        if not v or len(v.strip()) < 3:
            raise ValueError('用户名至少需要3个字符')
        if len(v) > 50:
            raise ValueError('用户名不能超过50个字符')
        return v.strip()
    
    @validator('password')
    def validate_password(cls, v):
        if len(v) < 6:
            raise ValueError('密码至少需要6个字符')
        return v


class UserLogin(BaseModel):
    """用户登录请求"""
    username: str
    password: str


class UserResponse(BaseModel):
    """用户响应"""
    user_id: int
    username: str
    email: str
    role_name: str
    is_active: bool
    created_time: datetime
    last_login_time: Optional[datetime]
    permissions: List[str]
    
    class Config:
        from_attributes = True


class TokenResponse(BaseModel):
    """Token响应"""
    access_token: str
    token_type: str = "bearer"
    expires_in: int
    user: UserResponse


class UserUpdate(BaseModel):
    """用户信息更新"""
    email: Optional[EmailStr] = None
    
    @validator('email')
    def validate_email(cls, v):
        if v is not None and not v.strip():
            raise ValueError('邮箱不能为空')
        return v


class PasswordChange(BaseModel):
    """密码修改"""
    old_password: str
    new_password: str
    
    @validator('new_password')
    def validate_new_password(cls, v):
        if len(v) < 6:
            raise ValueError('新密码至少需要6个字符')
        return v


class UserListResponse(BaseModel):
    """用户列表响应"""
    users: List[UserResponse]
    total: int
    page: int
    page_size: int


class RoleResponse(BaseModel):
    """角色响应"""
    role_id: int
    role_name: str
    role_description: Optional[str]
    created_time: datetime
    
    class Config:
        from_attributes = True


class PermissionResponse(BaseModel):
    """权限响应"""
    permission_id: int
    permission_name: str
    permission_description: Optional[str]
    created_time: datetime
    
    class Config:
        from_attributes = True


class UserCreateByAdmin(BaseModel):
    """管理员创建用户"""
    username: str
    email: EmailStr
    password: str
    role_id: int = 2  # 默认为普通用户
    
    @validator('username')
    def validate_username(cls, v):
        if not v or len(v.strip()) < 3:
            raise ValueError('用户名至少需要3个字符')
        if len(v) > 50:
            raise ValueError('用户名不能超过50个字符')
        return v.strip()
    
    @validator('password')
    def validate_password(cls, v):
        if len(v) < 6:
            raise ValueError('密码至少需要6个字符')
        return v


class UserUpdateByAdmin(BaseModel):
    """管理员更新用户"""
    email: Optional[EmailStr] = None
    role_id: Optional[int] = None
    is_active: Optional[bool] = None 